<?php
/**
 * 作者：云喵软件开发工作室
 * 官网：https://www.meoyun.com
 */

namespace app\adminapi\controller;

use app\model\AgreementModel;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use Webman\Http\Request;

class Agreement extends BaseAdminApi
{
    public function saveAgreement(Request $request)
    {
        $raw = $request->post();
        try {
            $params = v::input($raw, [
                'id' => v::notEmpty()->setName('协议ID'),
                'title' => v::stringType()->notEmpty()->length(1, 50)->setName('标题'),
                'content' => v::stringType()->notEmpty()->setName('内容'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $agreement = AgreementModel::find($params['id']);
            if (!$agreement) {
                return $this->fail('协议不存在');
            }

            $agreement->update([
                'title' => $params['title'],
                'content' => $params['content'],
            ]);

            return $this->success('协议更新成功');
        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }

    public function getAgreement(Request $request)
    {
        try {
            $params = v::input($request->get(), [
                'id' => v::notEmpty()->setName('协议ID'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        try {
            $agreement = AgreementModel::find($params['id']);

            return $this->success($agreement);
        } catch (\Exception $e) {
            return $this->fail('获取失败：' . $e->getMessage());
        }
    }

}